package com.qd.qx.ui.module1;

import android.content.Context;
import android.graphics.Color;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aspsine.irecyclerview.IRecyclerView;
import com.aspsine.irecyclerview.animation.ScaleInAnimation;
import com.aspsine.irecyclerview.universaladapter.ViewHolderHelper;
import com.aspsine.irecyclerview.universaladapter.recyclerview.CommonRecycleViewAdapter;
import com.qd.common.base.BaseFragment;
import com.qd.common.baserx.RxBus;
import com.qd.qx.R;
import com.qd.qx.api.MyXMPPTCPConnection;
import com.qd.qx.app.AppConstants;
import com.qd.qx.bean.PeopleBean;
import com.qd.qx.db.bean.MsgList;
import com.qd.qx.im.ImRxBus;
import com.qd.qx.im.ChatInfoUtils;
import com.qd.qx.im.imui.ImMenuPopwindow;
import com.qd.qx.ui.main.activity.ChatActivity;
import com.qd.common.commonutils.DateUtils;
import com.qd.chatui.util.MyUtils;
import com.qd.qx.widget.BadgeView;
import com.qd.qx.widget.NineGridImageView;
import com.qd.qx.widget.NineGridImageViewAdapter;

import org.jivesoftware.smack.packet.Message;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

/**
 * Code is far away from bug with the animal protecting
 * Author：ys on 2018/7/13
 * Function：消息模块
 */
public class MessageFragment extends BaseFragment {
    @BindView(R.id.messageIrcv)
    IRecyclerView messageIrcv;
    @BindView(R.id.ivBack)
    ImageView ivBack;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.ivMore)
    ImageView ivMore;
    @BindView(R.id.rl_state)
    RelativeLayout rlState;//头部状态布局
    private List<MsgList> groupUrlList = new ArrayList<>();
    CommonRecycleViewAdapter adapter;

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_message_layout;
    }

    @Override
    public void initPresenter() {

    }

    @Override
    public void initView() {
        ivBack.setVisibility(View.GONE);
        tvTitle.setText("消息");
        //添加一个搜索头
        View searchView = View.inflate(getActivity(), R.layout.searchview_layout, null);
        searchView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SearchActivity.startAction(getActivity());
            }
        });
        messageIrcv.addHeaderView(searchView);
        initRcv();
        ImRxBus.getInstance().toObserverable(Message.class).
                observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Message>() {
                    @Override
                    public void call(Message message) {
                        refreshList();
                    }
                });
    }


    private void initRcv() {
        groupUrlList = MyXMPPTCPConnection.getInstance().getDbHelper().getMsgAllList(MyXMPPTCPConnection.getInstance().GetUser().getUser_id());
        adapter = new CommonRecycleViewAdapter<MsgList>(getActivity(), R.layout.item_chatmessage_layout) {
            @Override
            public void convert(final ViewHolderHelper helper, MsgList msgObj) {
                TextView tvName = helper.getView(R.id.tvName);
                tvName.setText(msgObj.getRealName());
                TextView tvContent = helper.getView(R.id.tvContent);
                tvContent.setText(msgObj.getLast_msg());
                TextView tvTime = helper.getView(R.id.tvTime);
                if (TextUtils.isEmpty(msgObj.getLast_img_time())) {
                    tvTime.setText("");
                } else {
                    tvTime.setText(DateUtils.LongFormatTime(msgObj.getLast_img_time()));
                }

                RelativeLayout rl_chatView = helper.getView(R.id.rl_chatView);
                if (TextUtils.isEmpty(msgObj.getTop_time())) {
                    rl_chatView.setBackgroundColor(Color.parseColor("#ffffff"));
                } else {
                    rl_chatView.setBackgroundColor(Color.parseColor("#F0F8FF"));
                }

                final NineGridImageView nineGridImageView = helper.getView(R.id.nineImg);
                nineGridImageView.setAdapter(nineGridImageViewAdapter);
                final List<PeopleBean> stringList = new ArrayList<>();

                ChatInfoUtils.getInstance().getUserInfo(msgObj.getTo_name(), new ChatInfoUtils.ChatInfoCallBack() {
                    @Override
                    public void callBack(Object object) {
                        if (null != object) {
                            List<PeopleBean> imgList = (List<PeopleBean>) object;
                            stringList.addAll(imgList);
                        } else {
                            //stringList.add(new );
                        }
                        if (stringList.size() == 1) {
                            nineGridImageView.setGap(0);
                            nineGridImageView.setBackground(null);
                        }
                        nineGridImageView.setImagesData(stringList);
                    }
                });


                RelativeLayout rlBadge = helper.getView(R.id.rlBadge);
                //单消息 多消息 设置
                ImageView ivRedPoint = helper.getView(R.id.ivRedPoint);
                BadgeView badgeView = helper.getView(R.id.badgeView);
                if (1 == msgObj.getUnread_count()) {
                    ivRedPoint.setVisibility(View.VISIBLE);
                    badgeView.setVisibility(View.GONE);
                } else if (0 == msgObj.getUnread_count()) {
                    ivRedPoint.setVisibility(View.GONE);
                    badgeView.setVisibility(View.GONE);
                } else {
                    ivRedPoint.setVisibility(View.GONE);
                    badgeView.setVisibility(View.VISIBLE);
                    badgeView.setBadgeCount(msgObj.getUnread_count());
                }
            }

            @Override
            public void onBindViewHolder(final ViewHolderHelper holder, final int position) {
                super.onBindViewHolder(holder, position);
                //positon 从0开始
                RelativeLayout relativeLayout = holder.getView(R.id.rl_chatView);
                relativeLayout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ChatActivity.startAction(getActivity(), groupUrlList.get(position).getMsg_list_id(), groupUrlList.get(position).getTo_name(), groupUrlList.get(position).getRealName());
                    }
                });
                TextView delete = holder.getView(R.id.tvDelete);
                delete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        MyXMPPTCPConnection.getInstance().getDbHelper().deleteChat(groupUrlList.get(position).getMsg_list_id());
                        groupUrlList.clear();
                        groupUrlList = MyXMPPTCPConnection.getInstance().getDbHelper().getMsgAllList(MyXMPPTCPConnection.getInstance().GetUser().getUser_id());
                        if (null != adapter) {
                            adapter.clear();
                            adapter.addAll(groupUrlList);
                            messageIrcv.setAdapter(adapter);
                        }
                    }
                });
            }
        };
        messageIrcv.setLayoutManager(new LinearLayoutManager(getActivity()));
        adapter.addAll(groupUrlList);
        adapter.openLoadAnimation(new ScaleInAnimation());
        messageIrcv.setAdapter(adapter);
    }

    /**
     * 清空所有未读消息
     */
    public void markAllUnreadCount() {
        MyXMPPTCPConnection.getInstance().getDbHelper().markAllUnreadCount(MyXMPPTCPConnection.getInstance().GetUser().getUser_id());
        refreshList();
        RxBus.getInstance().post(AppConstants.REFRESH_ALLUNREADCOUNT, 0);
    }

    /**
     * 刷新列表
     */
    private void refreshList() {
        groupUrlList.clear();
        groupUrlList = MyXMPPTCPConnection.getInstance().getDbHelper().getMsgAllList(MyXMPPTCPConnection.getInstance().GetUser().getUser_id());
        if (null != adapter) {
            adapter.clear();
            adapter.addAll(groupUrlList);
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        refreshList();
    }

    /**
     * 头像9宫格适配器
     */
    private NineGridImageViewAdapter<PeopleBean> nineGridImageViewAdapter = new NineGridImageViewAdapter<PeopleBean>() {
        @Override
        protected void onDisplayImage(Context context, ImageView imageView, PeopleBean bean) {
            MyUtils.displayUserHeader(context, imageView, bean.getHeaderImg(), bean.getName());
        }

        @Override
        protected ImageView generateImageView(Context context) {
            return super.generateImageView(context);
        }
    };

    @OnClick({R.id.ivBack, R.id.tvTitle, R.id.ivMore})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ivBack:
                break;
            case R.id.tvTitle:
                break;
            case R.id.ivMore:
                new ImMenuPopwindow(getActivity(), this).showAtBottom(ivMore);
                break;
        }
    }
}
